//
//  LPCommonTool.m
//  DigitalSchool
//
//  Created by Pan on 2017/10/31.
//  Copyright © 2017年 Pan. All rights reserved.
//

/** 通用工具类 */

#import "LPCommonTool.h"
#import "pch.h"
static LPCommonTool *singleton = nil;
@implementation LPCommonTool


+ (instancetype)defaultSingleton {
    
    // GCD创建单例，效率更高，性能更好，消耗更低。
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton = [[LPCommonTool alloc] init];
    });
    return singleton;
}






/**
 @method 存储数据对象到本地userDefault
 */
+(void)writeUserDefaultObject:(NSObject*)object forKey:(NSString*)key {
    if (!object || !key)
    {
        return;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSObject *objc = object ; // set value
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:objc];
    [defaults setObject:data forKey:key];
    [defaults synchronize];
}

/**
 @method 获取userDefault对象
 */
+(id)readUserDefaultObjectForKey:(NSString*)key {
    if (key) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:key];
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    else {
        return nil;
    }
}

/**
 读写历史记录
 */
+(void)writeHisteryTimeObject:(NSObject*)object forKey:(NSString*)key{
    if (!object || !key)
    {
        return;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSObject *objc = object ; // set value
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:objc];
    [defaults setObject:data forKey:key];
    [defaults synchronize];
}

+(id)readhistoryForKey:(NSString*)key{
    if (key) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:key];
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    else {
        return nil;
    }
}

+(NSString*)timestampChangeTotime:(NSString *)str{
    //时间解析
    NSTimeInterval secondSince1970 = [str doubleValue] / 1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:secondSince1970];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"M-d- HH:mm"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}

+(NSString*)timestampChangeTotime_Two:(NSString *)str{
    //时间解析
    NSTimeInterval secondSince1970 = [str doubleValue] / 1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:secondSince1970];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy.MM.dd HH:mm"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}





/** long转日期 (返回日期字符串) */
+ (NSString *)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds formatter:(NSString *)formatter {
    
    NSDate *timeDate = [[NSDate alloc] initWithTimeIntervalSince1970:seconds / 1000.0];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = formatter;
    
    return [dateFormatter stringFromDate:timeDate];
}



/** 对象 转 Jason字符串 */
+ (NSString*)objectToJsonWithObject:(id)object {
    if (!object) {
        return nil;
    }
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/** Json 转 对象 */
+ (id)jsonToObjectWithJsonString:(NSString *)jsonString {
    if (jsonString == nil || [jsonString isKindOfClass:[NSNull class]]) {
        return nil;
    }
   // NSLog(@"请求结果：result = %@", jsonString);

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:jsonString,@"message",@"400",@"code",nil];
        NSLog(@"%@", dic);
        return dic;
    }
    return dic;
}


+ (NSNumber *)readphoneNumber {
    
    if ([LPCommonTool readUserDefaultObjectForKey:DSUSERKEY][@"phoneNumber"]) {
        NSDictionary *dic = [LPCommonTool readUserDefaultObjectForKey:DSUSERKEY];
        return @([dic[@"phoneNumber"] integerValue]);
    }
    return nil;
}

+(NSNumber *)readPassword{
    if ([LPCommonTool readUserDefaultObjectForKey:DSUSERKEY][@"password"]) {
        NSDictionary *dic = [LPCommonTool readUserDefaultObjectForKey:DSUSERKEY];
        return @([dic[@"password"] integerValue]);
    }
    return nil;
}

+(NSNumber *)readTime{
    if ([LPCommonTool readhistoryForKey:DSHISTERY][@"historyTime"]) {
        NSDictionary *dic = [LPCommonTool readUserDefaultObjectForKey:DSUSERKEY];
        return @([dic[@"historyTime"] integerValue]);
    }
    return nil;
}



+(NSNumber *)readIdengit{
    if ([LPCommonTool readUserDefaultObjectForKey:DSUSERKEY][@"identity"]) {
        NSDictionary *dic = [LPCommonTool readUserDefaultObjectForKey:DSUSERKEY];
        return @([dic[@"identity"] integerValue]);
    }
    return nil;
}


//判断是否输入了emoji 表情
+ (BOOL)stringContainsEmoji:(NSString *)string{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}

/**
 *  判断字符串中是否存在emoji
 * @param string 字符串
 * @return YES(含有表情)
 */
+ (BOOL)hasEmoji:(NSString*)string;
{
    NSString *pattern = @"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}

/**
 判断是不是九宫格
 @param string  输入的字符
 @return YES(是九宫格拼音键盘)
 */
+(BOOL)isNineKeyBoard:(NSString *)string
{
    NSString *other = @"➋➌➍➎➏➐➑➒";
    int len = (int)string.length;
    for(int i=0;i<len;i++)
    {
        unichar a=[string characterAtIndex:i];
        if(!((isalpha(a))
             ||(isalnum(a))
             //             ||((a=='_') || (a == '-')) //判断是否允许下划线，昵称可能会用上
             ||((a==' '))                 //判断是否允许控制
             ||((a >= 0x4e00 && a <= 0x9fa6))
             ||([other rangeOfString:string].location != NSNotFound)
             ))
            
        
        
//        if(!([other rangeOfString:string].location != NSNotFound))
            return NO;
        
    }
    return YES;
}






/** 正则表达式判断输入（中文、英文、数字、符号） */
+(BOOL)predicateString:(NSString*)string {
    
    // 空字符，删除键
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    NSString *other = @"➋➌➍➎➏➐➑➒";     //九宫格的输入值
    if ([other rangeOfString:string].location != NSNotFound) {
        // 九宫格输入
        return YES;
    }
    
    // 正则匹配字符串
    NSString *predicateString =@"[0-9a-zA-Z\u4e00-\u9fa5\\s\\.\\*\\)\\(\\+\\$\\[\\?\\\\\\^\\{\\|\\]\\}\\-\\￥\\`\\·\\～\\~%%%@\'\",。‘、-【】·.！_——=:;；<>《》‘’“”!#~·……&/?]+";
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",predicateString];
    
    BOOL isMatch = [predicate evaluateWithObject:string];
    
    return isMatch;
}


///** Label标签 */
//+(UILabel *)initLableWithMaxWidth:(CGFloat)maxWidth
//                           height:(CGFloat)height
//                           string:(NSString *)string
//                             font:(UIFont *)font
//                        textColor:(UIColor *)textColor
//                    numberOfLines:(int)numberOfLines
//                        sizfTofit:(BOOL)sizfTofit
//{
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, maxWidth, height)];
//    if ([string isKindOfClass:[NSNull class]]) {
//        string = @"";
//    }
//    if (string.length <= 0) {
//        string = @"";
//    }
//    label.text = string;
//    
//    label.font = font;
//    label.backgroundColor = [UIColor clearColor];
//    label.textColor = textColor;
//    label.numberOfLines = numberOfLines;
//    [label sizeToFit];
//    if (sizfTofit) {
//        if (CGRectGetWidth(label.bounds) > maxWidth) {
//            label.bounds = CGRectMake(0, 0, maxWidth, CGRectGetHeight(label.bounds));
//        }
//    }else{
//        label.bounds = CGRectMake(0, 0, maxWidth, height);
//    }
//    return label;
//}
@end
